package com.cloud.bssp.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

/**
 * @description： TODO
 * @author：weirx
 * @date：2021/7/20 17:34
 * @version：3.0
 */
public class TestCopyFileByNIO {

    public static void fileChannelCopy(String sfPath, String tfPath) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in;
        FileChannel out;
        try {
            fi = new FileInputStream(new File(sfPath));
            fo = new FileOutputStream(new File(tfPath));
            in = fi.getChannel();
            out = fo.getChannel();
            // 总文件大小
            long size = in.size();
            // left 剩余文件的数量
            for (long left = size; left > 0;){
                System.out.println("position = " + (size - left) + "，left = " + left);
                // transferTo返回传输的数量，剩余的减去传输的，就是当前剩余的数量
                left -= in.transferTo((size -left), left, out);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                fo.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String sPath = "E:\\workspace\\workspace.zip";
        String tPath = "E:\\workspace\\workspace-" + System.currentTimeMillis() + "-bak.zip";
        fileChannelCopy(sPath, tPath);
        long end = System.currentTimeMillis();
        System.out.println("用时为：" + (end - start) + "ms");
    }
}
